package cn.com.panda.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;



public class BitmapUtil {
    public static Bitmap temp;
    public final static String MEDIABASEURI = Environment.getExternalStorageDirectory()+ "/Pictures";

    /**
     * 根据指定的高度进行缩放（source是bitmap）
     */
    public static Bitmap bitmapZoomByHeight(Bitmap srcBitmap, float newHeight) {
        float scale = newHeight / (((float) srcBitmap.getHeight()));
        return BitmapUtil.bitmapZoomByScale(srcBitmap, scale, scale);
    }

    /**
     * 根据指定的高度进行缩放（source是drawable）
     */
    public static Bitmap bitmapZoomByHeight(Drawable drawable, float newHeight) {
        Bitmap bitmap = BitmapUtil.drawableToBitmap(drawable);
        float scale = newHeight / (((float) bitmap.getHeight()));
        return BitmapUtil.bitmapZoomByScale(bitmap, scale, scale);
    }

    /**
     * 根据指定的宽度比例值和高度比例值进行缩放
     */
    public static Bitmap bitmapZoomByScale(Bitmap srcBitmap, float scaleWidth, float scaleHeight) {
        int width = srcBitmap.getWidth();
        int height = srcBitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(srcBitmap, 0, 0, width, height, matrix, true);
        if (bitmap != null) {
            return bitmap;
        } else {
            return srcBitmap;
        }
    }

    /**
     * 将drawable对象转成bitmap对象
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 将drawable对象转成bitmap对象
     */
    public static Bitmap drawableToBitmap2(Drawable drawable) {
        BitmapDrawable bd = (BitmapDrawable) drawable;
        Bitmap bm = bd.getBitmap();
        return bm;
    }
    public static boolean saveImageToGallery(Context context, Bitmap bitmap){
        return saveImageToGallery(context,bitmap,"");
    }

    /**
     * 读取图片属性：旋转的角度(有些相机涉及到横屏。纵屏拍摄问题)
     *
     * @param path
     *            图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片按照某个角度进行旋转，解决拍照倒置的问题
     *
     * @param bm
     *            需要旋转的图片
     * @param degree
     *            旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }


    /**
     * 保存图片到指定路径
     *
     * @param context
     * @param bitmap  要保存的图片
     * @return true 成功 false失败
     */
    public static boolean saveImageToGallery(Context context, Bitmap bitmap,String subDir) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
             Toast.makeText(context,"sdcard未使用",Toast.LENGTH_SHORT).show();
             return false;
         }
        String descDir = "";
        if(TextUtils.isEmpty(subDir)){
            descDir = MEDIABASEURI + "/tianyi";
        }else
            descDir = MEDIABASEURI +"/tianyi"+ "/" + subDir;
        // 首先保存图片
         File appDir = new File(descDir);
         if (!appDir.exists()) {
             appDir.mkdirs();
         }

         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Date date = new Date(System.currentTimeMillis());
         String fileName = simpleDateFormat.format(date) + ".jpg";
        try {
         if(Build.VERSION.SDK_INT < Build.VERSION_CODES.Q){
             File file = new File(descDir + File.separator + fileName);

                 if(!file.exists())
                     file.createNewFile();
                 FileOutputStream fos = new FileOutputStream(file);
                 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                 fos.flush();
                 fos.close();

             // 最后通知图库更新
             galleryAddPic(context,file.getAbsolutePath());
         }else{
             ContentResolver resolver = context.getContentResolver();
             Uri uri = insertImageFileIntoMediaStore(context,fileName,"jpg","tianyi");
             ByteArrayOutputStream os = new ByteArrayOutputStream();
             if (bitmap != null) {
                 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                 bitmap.recycle();
             }
             OutputStream  outputStream = resolver.openOutputStream(uri);
             outputStream.write(os.toByteArray());
             os.flush();
         }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
         return  true;
    }

    /**
     * AndroidQ以上保存图片到公共目录
     *
     * @param imageName 图片名称
     * @param imageType 图片类型
     * @param relativePath 缓存路径
     */
    private static Uri insertImageFileIntoMediaStore (Context context,String imageName, String imageType,
                                                      String relativePath) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            return null;
        }
        if (TextUtils.isEmpty(relativePath)) {
            return null;
        }
        Uri insertUri = null;
        ContentResolver resolver = context.getContentResolver();
        //设置文件参数到ContentValues中
        ContentValues values = new ContentValues();
        //设置文件名
        values.put(MediaStore.Images.Media.DISPLAY_NAME, imageName);
        //设置文件描述，这里以文件名代替
        values.put(MediaStore.Images.Media.DESCRIPTION, imageName);
        //设置文件类型为image/*
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
        //注意：MediaStore.Images.Media.RELATIVE_PATH需要targetSdkVersion=29,
        //故该方法只可在Android10的手机上执行
//        values.put(MediaStore.Images.Media.RELATIVE_PATH, relativePath);
        //EXTERNAL_CONTENT_URI代表外部存储器
        Uri external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        //insertUri表示文件保存的uri路径
        insertUri = resolver.insert(external, values);
        return insertUri;
    }

    /**
     * 保存图片到指定路径
     *
     * @param context
     * @param bitmap  要保存的图片
     * @return true 成功 false失败
     */
    public static boolean saveImageToGallery(Context context, Bitmap bitmap,String subDir,String fileName) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(context,"sdcard未使用",Toast.LENGTH_SHORT).show();
            return false;
        }
        String descDir = "";
        if(TextUtils.isEmpty(subDir)){
            descDir = MEDIABASEURI + "/tianyi";
        }else
            descDir = MEDIABASEURI +"/tianyi"+ "/" + subDir;
        // 首先保存图片
        File appDir = new File(descDir);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }

        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

       /* // 其次把文件插入到系统图库
         try {
             MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
             e.printStackTrace();
             return false;
        } */
        // 最后通知图库更新
//         context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + "")));
        galleryAddPic(context,file.getAbsolutePath());
        return  true;
    }

    /**
     * 将图片保存到图库
     */
    public static void galleryAddPic(Context context, String currentPhotoPath) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(currentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }

    /**将bitmap对象保存成图片到sd卡中*/
    public static void saveBitmapToSDCard(Bitmap bitmap, String path) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, ((OutputStream)fileOutputStream));//设置PNG的话，透明区域不会变成黑色
            fileOutputStream.close();
            System.out.println("----------save success-------------------");
        }
        catch(Exception v0) {
            v0.printStackTrace();
        }
    }

    /**从sd卡中获取图片的bitmap对象*/
    public static Bitmap getBitmapFromSDCard(String path) {

        Bitmap bitmap = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(path);
            if(fileInputStream != null) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2; //当图片资源太大的适合，会出现内存溢出。图片宽高都为原来的二分之一，即图片为原来的四分一
                bitmap = BitmapFactory.decodeStream(((InputStream) fileInputStream), null, options);
            }
        } catch(Exception e) {
            return null;
        }

        return bitmap;
    }

    /**
     * 对TextView设置不同状态时其文字颜色
     * @param normal
     * @param focused
     * @param unable
     * @return
     */
    public static ColorStateList createColorStateList(int normal, int checked, int focused, int unable) {
        int[] colors = new int[] { checked, focused, normal, focused, unable, normal };
        int[][] states = new int[6][];
        states[0] = new int[] { android.R.attr.state_checked, android.R.attr.state_enabled };
        states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused };
        states[2] = new int[] { android.R.attr.state_enabled };
        states[3] = new int[] { android.R.attr.state_focused };
        states[4] = new int[] { android.R.attr.state_window_focused };
        states[5] = new int[] {};
        ColorStateList colorList = new ColorStateList(states, colors);
        return colorList;
    }

    public ArrayList<String> getPictures(final String strPath) {
        ArrayList<String> list = new ArrayList<String>();
        File file = new File(strPath);
        if (!file.exists())
            file.mkdirs();
        File[] allfiles = file.listFiles();
        if (allfiles == null) {
            return list;
        }
        for(int k = 0; k < allfiles.length; k++) {
            final File fi = allfiles[k];
            if(fi.isFile()) {
                int idx = fi.getPath().lastIndexOf(".");
                if (idx <= 0) {
                    continue;
                }
                String suffix = fi.getPath().substring(idx);
                if ((suffix.toLowerCase().equals(".jpg")||suffix.toLowerCase().equals(".png")) && fi.length() > 30*1024) {
                    list.add(fi.getPath());
                }
            }
        }
        return list;
    }

    public ArrayList<String> getVideos(final String strPath) {
        ArrayList<String> list = new ArrayList<String>();
        File file = new File(strPath);
        if (!file.exists())
            file.mkdirs();
        File[] allfiles = file.listFiles();
        if (allfiles == null) {
            return list;
        }
        for(int k = 0; k < allfiles.length; k++) {
            final File fi = allfiles[k];
            if(fi.isFile()) {
                int idx = fi.getPath().lastIndexOf(".");
                if (idx <= 0) {
                    continue;
                }
                String suffix = fi.getPath().substring(idx);
                if (suffix.toLowerCase().equals(".mp4")) {
                    list.add(fi.getPath());
                }
            }
        }
        return list;
    }

}
